const mongoose = require('mongoose')
const joi = require('joi')

const userSchema = new mongoose.Schema({
    uname: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10
    },
    pwd: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true   // 保证唯一
    },
    role: {  // normal  普通用户    admin  管理员
        type: String,
        enum: ['normal', 'admin'],
        default: 'normal'
    },
    status: {  // 0 禁用  1 启用
        type: Number,
        enum: [0, 1],
        default: 1
    }
}, { versionKey: false });

const User = mongoose.model('User', userSchema, 'User');

const addUserValidate = user => {
    const schema = {
        uname: joi.string().required().min(2).max(10).error(new Error('用户名不符合验证规则')),
        pwd: joi.string().required().min(6).max(16).error(new Error('密码不符合验证规则')),
        email: joi.string().required().email().error(new Error('密码不符合验证规则')),
        role: joi.string().required().valid('normal', 'admin').error(new Error('角色不符合验证规则')),
        status: joi.number().required().valid(0, 1).error(new Error('状态不符合验证规则'))
    }
    return joi.validate(user, schema)
}

const editUserValidate = user => {
    const schema = {
        id: joi.string().required().error(new Error('用户id非法')),
        uname: joi.string().required().min(2).max(10).error(new Error('用户名不符合验证规则')),
        pwd: joi.string().required().regex(/^\w{6,16}$/).error(new Error('密码不符合验证规则')),
        email: joi.string().required().email().error(new Error('密码不符合验证规则')),
        role: joi.string().required().valid('normal', 'admin').error(new Error('角色不符合验证规则')),
        status: joi.number().required().valid(0, 1).error(new Error('状态不符合验证规则'))
    }
    return joi.validate(user, schema)
}

/* ;(async () => {
    await User.create({
        uname: 'tttttyo',
        pwd: 'qwer1234',
        email: 'tttttyo@qq.com',
        role: 'admin',
        status: '1'
    })
    console.log('默认用户创建成功！');
})() */

module.exports = { User, addUserValidate, editUserValidate };